package com.ctshk.rpc.order.tour.task;

import com.ctshk.common.constant.RedisConstants;
import com.ctshk.common.dto.Result;
import com.ctshk.rpc.user.service.IUserSmsService;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@Data
@Slf4j
@Component
public class SmsTask implements Runnable {

    private RedisTemplate<String, String> redisTemplate;

    private IUserSmsService userSmsService;

    private ScheduledExecutorService scheduledExecutorService;

    private Map<String, String> smsParam;

    @ApiModelProperty(value = "电话区号（C端）")
    private String phoneCode;

    @ApiModelProperty(value = "电话（C端）")
    private String phone;

    @ApiModelProperty(value = "业务类型")
    private Integer businessType;

    @Override
    public void run() {
        try {
            String orderid = smsParam.get("orderid");
            if (redisTemplate.hasKey(RedisConstants.TOUR_SCHEDULE_SMS + orderid)) {
                Integer num = Integer.parseInt(redisTemplate.opsForValue().get(RedisConstants.TOUR_SCHEDULE_SMS + orderid));
                log.info("【旅行团支付-支付回调】, 发送第{}次短信通知, param:{}", num, smsParam);
                Result smsResult = userSmsService.sendOrderSms(businessType, phoneCode, phone, smsParam);
                log.info("【旅行团支付-支付回调】, 短信通知结果:{}", smsResult.isSuccess());
                if (smsResult.isSuccess() || ++num == 3) {
                    scheduledExecutorService.shutdown();
                }
                redisTemplate.opsForValue().set(RedisConstants.TOUR_SCHEDULE_SMS + orderid, num + "", 5, TimeUnit.MINUTES);
            } else {
                scheduledExecutorService.shutdown();
            }
        } catch (Exception e) {
            log.info("【旅行团支付-支付回调】, 短信通知出现异常:{},任务关闭", e);
            scheduledExecutorService.shutdown();
        }
    }
}
